package com.qfedu.common.minio.utils;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * minio工具类
 */
@Component
public class MinioUtil {

    @Value("${minio.endpoint}")
    private String endpoint; // MinIO服务的URL，如：http://localhost:9000

    @Value("${minio.bucketName}")
    private String bucketName;

    @Autowired
    private MinioClient minioClient;

    /**
     * 判断bucket是否存在，不存在则创建
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传到桶中的upload文件夹
     *
     * @param file     上传的文件
     * @param filename
     * @return 上传后的完整HTTP访问路径
     */
    public String upload(MultipartFile file, String filename) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        // 如果桶不存在，直接创建
        existBucket(bucketName);

        // 获取原始文件名
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new RuntimeException("文件名为空");
        }
        System.out.println("原始文件名: " + fileName);

        // 修改文件名，增加UUID前缀避免冲突
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replace("-", "") + fileExtension;

        // 构建对象路径，指定上传到upload文件夹
        String objectPath = "upload/" + newFileName;

        try (InputStream in = file.getInputStream()) {
            // 上传到minio
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectPath)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            System.out.println("文件上传成功: " + objectPath);

            // 构建完整的HTTP访问路径
            String fullUrl = endpoint + "/" + bucketName + "/" + objectPath;
            System.out.println("完整访问URL: " + fullUrl);

            return fullUrl;
        } catch (Exception e) {
            System.err.println("MinIO上传失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }
}
